<template>
  <div class="menu">
    <page-content
      :tableConfig="tableConfig"
      title="菜单"
      pageName="menu"
      @newBtnClickEvent="handleNewBtnClick"
      @editBtnEventClick="handleEditBtnClick"
    ></page-content>
    <page-model
      ref="pageModelRef"
      :modelConfig="modelConfigRef"
      :defalultInfo="pageModelInfo"
      @formDataChange="formDataChange"
      pageName="menu"
    >
    </page-model>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref } from 'vue'
import { tableConfig } from './config/content.config'

import { modelConfig } from './config/model.config'
import { usePageModel } from '@/hooks/use-page-model'

import { useStore } from 'vuex'
import { filterMenus } from '@/utils/map-menu'

export default defineComponent({
  name: 'my-menu',
  setup() {
    //1:从pagemodel hook导入公共函数
    const [pageModelInfo, pageModelRef, handleEditBtnClick, handleNewBtnClick] =
      usePageModel()

    //2:
    const store = useStore()

    //3:监听菜单类型改变
    const formItemTypeRef = ref(0)

    const modelConfigRef = computed(() => {
      //1:处理下上级菜单
      const parentIdItem = modelConfig.formItems.find(
        (item) => item.field == 'parentId'
      )
      if (formItemTypeRef.value == 1) {
        parentIdItem!.isHidden = true
      } else {
        parentIdItem!.isHidden = false
        parentIdItem!.options = filterMenus(
          store.state.allMenuList,
          formItemTypeRef.value - 1
        ).map((item) => {
          return { title: item.name, value: item.id, id: item.id }
        })
      }

      console.log('parentIdItem=', parentIdItem)
      return modelConfig
    })

    const formDataChange = (data: any) => {
      console.log('监听的model是', data)
      if (Object.keys(data.oldValue).length > 0) {
        if (data.newValue.type != data.oldValue.type) {
          data.newValue.parentId = ''
        }
      }

      formItemTypeRef.value = data.newValue.type ?? 1
    }

    return {
      tableConfig,
      modelConfigRef,
      pageModelRef,
      pageModelInfo,
      handleEditBtnClick,
      handleNewBtnClick,
      formDataChange,
      formItemTypeRef
    }
  }
})
</script>

<style scoped></style>
